package com.gisuni.sddc.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;

public class UtilMethod {
	/**
	 * 构造SQL查询硬编码，返回查询后结果
	 * 
	 * @param strSql
	 * @return
	 */
	public static List<Map<String, Object>> getFromSql(Dao dao,String strSql) {
		Sql sql = Sqls.create(strSql);
		sql.setCallback(new SqlCallback() {
			public Object invoke(Connection conn, ResultSet rs, Sql sql)
					throws SQLException {
				ResultSetMetaData rsmd = rs.getMetaData();
				int count = rsmd.getColumnCount();
				List<Map<String,Object>> ltMap = new LinkedList<Map<String,Object>>();
				while (rs.next()){
					Map<String,Object> map = new LinkedHashMap<String,Object>();
					for (int i = 1; i <= count; i++) {
						String col = rsmd.getColumnLabel(i);
						map.put(col, rs.getString(col));
					}
					ltMap.add(map);
				}
				return ltMap;
			}
		});
		dao.execute(sql);
		List<Map<String,Object>> lt = sql.getObject(List.class);
		return lt;
	}
	public static List<Map<String, Object>> getFromAdvQuerySql(Dao dao,String strSql){
		Sql sql = Sqls.create(strSql);
		sql.setCallback(new SqlCallback() {
			public Object invoke(Connection conn, ResultSet rs, Sql sql)
					throws SQLException {
				String col= rs.getMetaData().getColumnLabel(1);
				List<Map<String,Object>> ltMap = new LinkedList<Map<String,Object>>();
				LinkedHashSet<Object> lhs = new LinkedHashSet<Object>();
				while (rs.next()){
					Map<String,Object> map = new LinkedHashMap<String,Object>();
					lhs.add(rs.getObject(col));
				}
				for (Object str : lhs) {
					Map<String,Object> map = new LinkedHashMap<String,Object>();
					map.put(col, str);
					ltMap.add(map);
				}
				return ltMap;
			}
		});
		dao.execute(sql);
		List<Map<String,Object>> lt = sql.getObject(List.class);
		return lt;
	}
}
